/*
 * @Author: sean_kei@163.com
 * @Date: 2021-11-23 15:34:01
 * @LastEditors: sean_kei@163.com
 * @LastEditTime: 2021-12-01 16:56:45
 */
package com.wxhandle.cleandemo.sso.oauth2.provider;

import java.util.LinkedHashMap;

import com.wxhandle.cleandemo.core.domain.identity.SysUser;
import com.wxhandle.cleandemo.sso.entity.CarbonUser;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

/*
 * @Author: sean_kei@163.com
 * @Date: 2021-11-23 15:34:01
 * @LastEditors: sean_kei@163.com
 * @LastEditTime: 2021-11-23 15:44:18
 */
@Component
public class WeixinAuthenticationProvider implements AuthenticationProvider {

    @Autowired
    private UserDetailsService userService;
    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        String userName = authentication.getName();
        String rawPwd = (String) authentication.getCredentials();
        String unionId = "";
        CarbonUser user = (CarbonUser) userService.loadUserByUsername(userName);
        if(authentication.getDetails() instanceof LinkedHashMap){
            LinkedHashMap<String, String> map = (LinkedHashMap<String, String>) authentication.getDetails();
            if(map.containsKey("union_id")){
                unionId = map.get("union_id").toString();
                if(!unionId.equals(user.getUnionId())){
                    throw new BadCredentialsException("认证失败");
                } 
            }else{
                PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
                if(!encoder.matches(rawPwd, user.getPassword())){
                    throw new BadCredentialsException("用户名或密码错误");
                }
            }
        }

        
        return new UsernamePasswordAuthenticationToken(user,rawPwd, user.getAuthorities());
    }

    @Override
    public boolean supports(Class<?> authentication) {
        return authentication.equals(UsernamePasswordAuthenticationToken.class);
    }

}
